<template>
  <div class="emoji-generator">
    <el-card class="generator-card">
      <template #header>
        <div class="card-header">
          <h2>表情包生成器</h2>
          <p class="subtitle">输入文本描述，快速生成个性化表情包</p>
        </div>
      </template>

      <el-form :model="formData" :rules="rules" ref="formRef" label-position="top">
        <el-form-item label="文本描述" prop="text">
          <el-input
            v-model="formData.text"
            type="textarea"
            :rows="3"
            placeholder="请输入要生成的表情包描述，例如：开心的熊猫"
            :maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="生成风格" prop="style">
          <el-select v-model="formData.style" placeholder="请选择生成风格" style="width: 100%">
            <el-option label="卡通风格" value="cartoon">
              <template #default="{ label }">
                <el-icon><Picture /></el-icon>
                <span>{{ label }}</span>
              </template>
            </el-option>
            <el-option label="写实风格" value="realistic">
              <template #default="{ label }">
                <el-icon><Camera /></el-icon>
                <span>{{ label }}</span>
              </template>
            </el-option>
            <el-option label="艺术风格" value="artistic">
              <template #default="{ label }">
                <el-icon><Brush /></el-icon>
                <span>{{ label }}</span>
              </template>
            </el-option>
            <el-option label="动漫风格" value="anime">
              <template #default="{ label }">
                <el-icon><Star /></el-icon>
                <span>{{ label }}</span>
              </template>
            </el-option>
            <el-option label="漫画风格" value="comic">
              <template #default="{ label }">
                <el-icon><Collection /></el-icon>
                <span>{{ label }}</span>
              </template>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            :loading="generating" 
            :disabled="generating"
            @click="generateEmoji"
            style="width: 100%"
          >
            {{ generating ? '生成中...' : '生成表情包' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 生成结果 -->
      <div v-if="result" class="result-container">
        <el-image 
          :src="result.image_url"
          :preview-src-list="[result.image_url]"
          fit="contain"
          style="width: 100%; max-width: 512px"
        >
          <template #placeholder>
            <div class="image-placeholder">
              <el-icon><Picture /></el-icon>
              <span>加载中...</span>
            </div>
          </template>
          <template #error>
            <div class="image-placeholder">
              <el-icon><Warning /></el-icon>
              <span>加载失败</span>
            </div>
          </template>
        </el-image>

        <div class="action-buttons">
          <el-button-group>
            <el-button 
              type="primary"
              @click="downloadImage"
              :loading="downloading"
            >
              <el-icon><Download /></el-icon>
              下载
            </el-button>
            <el-button 
              type="success"
              @click="showShareDialog"
            >
              <el-icon><Share /></el-icon>
              分享
            </el-button>
            <el-button 
              type="info"
              @click="regenerate"
            >
              <el-icon><RefreshRight /></el-icon>
              重新生成
            </el-button>
          </el-button-group>
        </div>
      </div>
    </el-card>

    <!-- 分享对话框 -->
    <share-dialog
      v-model="shareDialogVisible"
      :image-url="result?.image_url"
      :image-id="result?.history_id"
    />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Picture, Camera, Brush, Star, Collection,
  Download, Share, RefreshRight, Warning
} from '@element-plus/icons-vue'
import ShareDialog from './ShareDialog.vue'
import request from '@/utils/request'

const API_BASE_URL = 'http://localhost:5000'

const formRef = ref(null)
const generating = ref(false)
const downloading = ref(false)
const shareDialogVisible = ref(false)

const formData = reactive({
  text: '',
  style: 'cartoon'
})

const rules = {
  text: [
    { required: true, message: '请输入文本描述', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ],
  style: [
    { required: true, message: '请选择生成风格', trigger: 'change' }
  ]
}

const result = ref(null)

// 生成表情包
const generateEmoji = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    generating.value = true
    ElMessage.info('正在生成表情包，请稍候...')
    
    const response = await request.post('/generate', {
      text: formData.text,
      style: formData.style
    })
    
    if (response.status === 'success') {
      result.value = response.data
      ElMessage.success('生成成功')
    } else {
      ElMessage.error(response.message || '生成失败')
    }
  } catch (error) {
    console.error('Generate error:', error)
    ElMessage.error(error.message || '生成失败')
  } finally {
    generating.value = false
  }
}

// 下载图片
const downloadImage = async () => {
  if (!result.value?.image_url) return
  
  downloading.value = true
  try {
    const response = await request.get(result.value.image_url, {
      responseType: 'blob'
    })
    const url = window.URL.createObjectURL(response.data)
    const link = document.createElement('a')
    link.href = url
    link.download = `emoji_${result.value.history_id}.png`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('下载成功')
  } catch (error) {
    ElMessage.error('下载失败')
  } finally {
    downloading.value = false
  }
}

// 显示分享对话框
const showShareDialog = () => {
  if (!result.value) return
  shareDialogVisible.value = true
}

// 重新生成
const regenerate = () => {
  result.value = null
  generateEmoji()
}
</script>

<style scoped>
.emoji-generator {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.generator-card {
  margin-bottom: 20px;
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
}

.subtitle {
  margin: 10px 0 0;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.el-select :deep(.el-input__wrapper) {
  padding-left: 12px;
}

.el-select :deep(.el-select-dropdown__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

.result-container {
  margin-top: 30px;
  text-align: center;
}

.image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: var(--el-text-color-secondary);
}

.image-placeholder .el-icon {
  font-size: 48px;
  margin-bottom: 8px;
}

.action-buttons {
  margin-top: 20px;
}

.el-button-group {
  display: inline-flex;
}

.el-button-group .el-button {
  margin: 0;
}
</style>